import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { type RouteRecordRaw } from "vue-router"
import { constantRoutes, asyncRoutes } from "@/router"
import asyncRouteSettings from "@/config/async-route"
import { IApiResponseUserRoles } from "@/api/login/types/login"

// const hasPermission = (roles: IApiResponseUserRoles[], route: RouteRecordRaw) => {
//   // 固定式权限
//   const routeRoles = route.meta && route.meta.roles
  
//   return routeRoles ? roles.some(role => routeRoles.includes(role)) : true
// }

  const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: IApiResponseUserRoles[]) => {
    const res: RouteRecordRaw[] = []
    const buttonAuthObject = {} // 按钮权限对象
    const pageObject = {} // 页面权限对象
    // 取出按钮权限
     roles.forEach((role) =>{
      if(role.node_type == 3){
        console.log(role.key)
        // buttonAuthObject[]
      }
     })
     // 模块按钮




    routes.map((route) => {
      let tmp = { ...route }
      tmp.hidden = true
      let item = roles[roles.findIndex((v)=>v.key ===  tmp.key)]
      tmp.hidden = item ? false : true
      if(tmp.children){
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    })
    // localStorage.setItem('routes',JSON.stringify(roles))
    return res
  }

  export const usePermissionStore = defineStore("permission", () => {
    // 可访问的路由
    const routes = ref<RouteRecordRaw[]>([])
    // 有访问权限的动态路由
    const dynamicRoutes = ref<RouteRecordRaw[]>([])
  
    const setRoutes = (roles: IApiResponseUserRoles[] ) => {
      let accessedRoutes
      if (!asyncRouteSettings.open) {
        accessedRoutes = asyncRoutes
      } else {
        
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      routes.value = constantRoutes.concat(accessedRoutes)
    }
  
    return { dynamicRoutes, setRoutes, routes  }
  })


  /** 在 setup 外使用 */
export function usePermissionStoreHook() {
    return usePermissionStore(store)
  }